package com.margo.project.web.workbench.interceptor;

import java.lang.reflect.Method;
import java.util.List;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.annotation.AnnotationUtils;


import com.margo.project.web.workbench.done.WorkbenchDone;
import com.margo.project.web.workbench.todo.WorkbenchTodo;
import com.margo.project.web.workbench.todo.WorkbenchTodoUser;

public class WorkbenchInterceptor implements MethodInterceptor,ApplicationContextAware{
	
	
	Logger logger=LoggerFactory.getLogger(WorkbenchInterceptor.class);
	
	private ApplicationContext applicationContext;
	
	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		this.applicationContext=applicationContext;	
	}

	@Override
	public Object invoke(MethodInvocation invocation) throws Throwable {
		Object value;
		try {
			value=invocation.proceed();
			//发送待办消息
			Method method=invocation.getMethod();
			Object[] arrParam=invocation.getArguments();
			//发送待办
			WorkbenchTodo todo = AnnotationUtils.findAnnotation(method, WorkbenchTodo.class);
			if(todo!=null) {
				String processId = todo.processId();
				Class<? extends WorkbenchTodoUser> cla=todo.implCls();
				if(cla !=WorkbenchTodoUser.class) {
					getTodoUserList(arrParam,cla);
				}
				logger.info("流程实例:"+processId);
				logger.info("参数个数:"+arrParam.length);
			}
			//发送已办
			WorkbenchDone done = AnnotationUtils.findAnnotation(method, WorkbenchDone.class);
			if(done!=null) {
				String processId = done.processId();
				logger.info("流程实例:"+processId);
				logger.info("参数个数:"+arrParam.length);
			}
		}
		catch (Throwable ex) {
			logger.info(ex.getMessage(),ex);
			throw new RuntimeException(ex);
		}
		return value;
	}
	
	private List<String> getTodoUserList(Object[] arrParam,Class<? extends WorkbenchTodoUser> cla) {
		WorkbenchTodoUser todoUserInterface=applicationContext.getBean(cla);
		List<String> lstUser=todoUserInterface.getUserList(arrParam);
		return lstUser;
	}

	public void sendTodoMessage() {
		logger.info("发送待办消息");
	}
	
	public void sendDoneMessage() {
		logger.info("发送已办消息");
	}

}
